<?php
require COMMON_PATH.'crypt.php';

class UserModel extends Model {
    protected $fields=array(
        'id','account', 'password','role', 'realname', 'email', 'created','status',
        '_pk'=>'id',
        '_autoInc'=>false
    );

    protected $_auto=array(
        array('account','trim','ALL','function'),
        array('realname','trim','ALL','function'),
        array('password','cryptUserPassword','ALL','function')
    );

    /**
     *  表单验证
     *  array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
     *  验证条件：0 存在就验证（默认），1必须验证，2什不为空就验证
     */
    protected $_validate=array(
        array('role','require','所属角色不能为空'),
        array('account','/^[a-zA-Z][a-zA-Z0-9_@-]{0,15}$/','用户名填写不正确'),
        array('password','/^.{6,}$/','密码长度必须在６位以上',2),
        array('realname','require','真实姓名填写不正确')
    );

    /**
     * 添加用户，成功返回用户信息，失败返回false
     */
    public function addUser() {/*{{{*/
        $vo=$this->create();
        if(!$vo) {
            return false;
        }
        if(!$this->checkRoleExist($vo['role'])) {
            $this->error='角色信息不存在';
            return false;
        }
        $checkUserRs=$this->where("account='{$vo['account']}' and status>0")->find();
        if(false===empty($checkUserRs)) {
            $this->error='用户名<b>'.$vo['account'].'</b>已经被使用';
            return false;
        }
        $vo['created']=date('Y-m-d H:i:s');
        $vo['status']=1;
        $this->startTrans();
        if($this->add($vo)) {
            $this->commit();
            return $vo;
        }
        $this->rollback();
        $this->error='添加用户失败';
        return false;
    }/*}}}*/

    public function updateMyself(){/*{{{*/
        $vo=$this->create();
        if(!$vo){
            return false;
        }
        if(empty($_POST['password'])){
            $vo=array_diff_key($vo,array('password'=>''));
        }else{
            //TODO 修改密码时要验证原密码
        }
        if($this->save($vo,"id={$vo['id']}")){
            $_SESSION[C('USER_AUTH_KEY')]=array_merge($_SESSION[C('USER_AUTH_KEY')], $vo);
            return true;
        }
        $this->error=UPDATE_FAIL;
        return false;
    }/*}}}*/

    /**
     * 更新用户信息
     */
    public function updateUser() {/*{{{*/
        $vo=$this->create();
        if(!$vo){
            return false;
        }
        if( ! $this->where("id={$vo['id']} and status>0")->find() ) {
            $this->error='用户信息没有找到';
            return false;
        }
        if(!$this->checkRoleExist($vo['role'])) {
            $this->error='角色信息不存在';
            return false;
        }
        //决定是否要修改密码
        if(empty($vo['password'])){
            $vo=array_diff_key($vo,array('password'=>''));
        }
        $this->startTrans();
        if($this->save($vo,"account='{$vo['account']}'")) {
            $this->commit();
            return $vo;
        }
        $this->rollback();
        $this->error=UPDATE_FAIL;
        return false;
    }/*}}}*/

    public function removalUser($uids){
        $this->startTrans();
        $tp=$this->tablePrefix;
        //先从其他表开始删
        if( false!==$this->query("delete from {$tp}category_user where userid in ({$uids})") &&
            false!==$this->query("delete from {$tp}user_options where userid in ({$uids})") &&
            false!==$this->query("update {$tp}user set status=0 where id in ({$uids})")){
            $this->commit();
            return true;
            }
        $this->rollback();
        return false;
    }

    /**
     * 检查角色是否存在
     */
    private function checkRoleExist($role) {
        $rs=$this->query('select * from '.$this->tablePrefix.'role where id=\''.$role.'\'');
        if(empty($rs)){
            return false;
        }
        return true;
    }

    /**
     * 用户登录，登录成功返回true,失败返回false
     */
    public function doLogin() {/*{{{*/
        $_POST['account']=$_POST['userid'];
        $_POST['password']=$_POST['pwd'];
        $userVo=$this->create();
        if(!$userVo) {
            $this->error='获取人员信息失败';
            return false;
        }
        $userRs=$this->where("account='{$userVo['account']}' and status>0")->find();
        if(!$userRs) {
            $this->error='用户<b>'.$userVo['account'].'</b>不存在';
            return false;
        }
        if($userRs['password']!==$userVo['password']) {
            $this->error='密码不正确';
            return false;
        }
        RBAC::saveAccessList($userRs['role']);
        //扩展角色信息
        $roleRs=$this->field('name')->where('id='.$userRs['role'])->table($this->tablePrefix.'role')->find();
        $userRs['roleName']=$roleRs['name'];
        //检查是否是最高管理员角色，即免认证管理员角色
        if(in_array($roleRs['name'],C('not_auth_role'))){
            $_SESSION[C('admin_auth_key')]=true;
        }
        //事件记录
        $eventDao=getEventDao();
        $latestLogin=$eventDao->findLastestEvent($userRs['id'],'LOGIN');
        if($latestLogin) {
            $_SESSION[C('USER_AUTH_KEY')]=array_merge($userRs,$latestLogin);
        }else {
            $_SESSION[C('USER_AUTH_KEY')]=$userRs;
        }
        $notAuthRole=C('not_auth_role');
        if( is_array($notAuthRole) && in_array($userRs['role'],$notAuthRole) ) {
            $_SESSION[C('ADMIN_AUTH_KEY')]=true;
        }
        $eventDao->logEvent($userRs['id'],'LOGIN',array(
            'DATE'=>NOW,
            'IP'=>get_client_ip(),
        ));
        return true;
    }/*}}}*/
}
